import React from 'react';
import { Button, Card, Dropdown, Form, Menu, message, Modal, Table, Upload } from 'antd';
import { connect } from 'umi';
import xss from 'xss';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import DataUpdate from '@/components/DataUpdate';
import Pagination from '@/components/Pagination';
import authHelper from '@/utils/auth/helper';
import { download } from '@/utils/utils';
import request from '@/utils/request';
import { AnchorPart, AnchorTableHeader } from '@/components/AnchorWrapper';
import {
    checkBeforeUpload,
    downTemplate,
    downTemplateVv,
    fetchPostApply,
    fetchVersionApply
} from '@/services/setting/salaryReference';
import { history } from 'umi'
import cookie from 'js-cookie';
import { hasWorkFlowByType } from '@/pages/WorkFlow/utils';
import { eventTrack } from '@/utils/track';
import SalaryDescription from './SalaryDescription';
import QuickSearch from './QuickSearch';
import styles from './index.less';
import { useEditionDetailList, useEditionList } from './hooks';

const { checkCode } = authHelper;
const description = {
    title: '帮助提示',
    cont:
        "<div><span style='color:#FF4000'}>红色</span>表示与前一版本相比删除的内容，<span style='color:#00C800'>绿色</span>表示与前一版本相比新增的内容，<span style='color:#BCA3EF' >紫色</span>表示与前一版本相比更新的内容。</div>"
};

const expandStyle = {
    display: 'inline-block',
    fontSize: '16px',
    border: '1px solid #eee',
    height: '17px',
    width: '16px',
    lineHeight: '12px',
    paddingLeft: '2px',
    textAlign: 'center',
    verticalAlign: 'middle'
};

/**
 * 薪资参考/职位映射 公用的一个页面
 *
 * 注意: 因为两个业务被写进同一个页面, 所以一些关键操作有座特殊判断. Σ(⊙▽⊙"a
 */
const History = ({ form, user, route }) => {
    // 该页面与职级映射公用 慎改哦~ 注意expkeys状态维护
    const { path } = route;
    // const { query } = location;
    const urlType =
        path === '/office/personnelManagement/organization/dataManagement/salaryReference' ? 'salary' : 'post';
    const { currentUser } = user;
    const [activeIndex, setActiveIndex] = React.useState(0); // 选中高亮效果
    const [version, setVersion] = React.useState(''); // 当前版本值
    const [search, setSearch] = React.useState(1);
    const [backVersion, setBackVersion] = React.useState(0);
    const [sortCustom, setSortCustom] = React.useState(''); // 排序 筛选功能
    const [expkeys, setExpkeys] = React.useState([]); // 控制详情表格F展开项
    const [filterDataName, setFilterDataName] = React.useState([]);
    const [filterType, setFilterType] = React.useState('weiwei');

    const [pagination, setPagination] = React.useState({
        current: 1,
        pageSize: 100
        // total: 10
    }); // 分页
    /* 根据流程是否处于审批，判断是否能上传 */
    const [uploadDisabled, setUploadDisabled] = React.useState(false);
    const [applicationNo, setApplicationNo] = React.useState('');
    const [editionLoading, editionData] = useEditionList({ setVersion, urlType, setApplicationNo }); // 版本列表数据
    const values = form.getFieldsValue();
    const payloads = {
        changeType: 1,
        // companyId: currentUser.companyId || '',
        // departmentId: currentUser.departmentId || '',
        // employeeId: currentUser.id || '',
        version,
        searchName: values.searchName || '',
        searchType: values.searchType || ''
    };
    const [loading, dataSource] = useEditionDetailList({
        // version,
        search,
        pagination,
        payloads,
        setPagination,
        urlType,
        sortCustom,
        setExpkeys,
        filterDataName
    }); // 版本列表详情数据

    const [dict, setDict] = React.useState([]); // 获取表格筛选下拉数据

    // 薪资参考的流程Url
    const [salaryWorkFlowUrl, setSalaryWorkFlowUrl] = React.useState(null);

    // 检查流程是否存在
    const checkSalaryWorkFlow = async () => {
        try {
            const { workFlowUrl } = await hasWorkFlowByType('SalaryApply', false); // 检查是否有该流程
            setSalaryWorkFlowUrl(workFlowUrl || false);
        } catch (e) {
            setSalaryWorkFlowUrl(null);
        }
    };

    // 恢复此版本跳转方法
    const handleBackVersion = async () => {
        const payLoad = {
            [urlType === 'salary' ? 'salaryStandardVersion' : 'postitionSalaryVersion']: version
        };
        const result = urlType === 'salary' ? await fetchVersionApply(payLoad) : await fetchPostApply(payLoad);
        if (result && result.code === 10000) {
            // 跳转到流程页面
            history.push(`${salaryWorkFlowUrl}${result.data.hiDataId}&version=${result.data.version}&ftype=rollback`);
        } else {
            message.warn('当前有数据变更申请在进行中，请先完成相关审批！');
        }
    };
    const linkOld = record => {
        const authCode = urlType === 'salary' ? 'system:data:salary:upload' : 'system:data:post:upload';
        return checkCode(authCode) ? (
            <a
                onClick={() => {
                    if (urlType === 'salary') {
                        if (salaryWorkFlowUrl) {
                            // 检查流程是否存在
                            setVersion(record.salaryStandardVersion);
                            setBackVersion(backVersion + 1);
                        } else if (salaryWorkFlowUrl === false) {
                            message.warn('没有相关的审批流程！');
                        } else {
                            message.warn('正在检测是否有相关审批流程, 请稍等!');
                        }
                    } else {
                        setVersion(record.postitionSalaryVersion);
                        setBackVersion(backVersion + 1);
                    }
                }}
            >
                恢复此版本
            </a>
        ) : null;
    };
    /**
     * 新增下载导入功能  ---从别的地方照搬过来的
     * start
     */

    // 下载模板 市场
    const downloadTemp = async () => {
        const response = await downTemplate();
        download({
            getData: () => response
        });
    };
    // 下载模板 微微
    const downloadTempVv = async () => {
        const response = await downTemplateVv();
        download({
            getData: () => response
        });
    };
    // 导入
    const downMenuItem = () => (
        <Menu>
            <Menu.Item>
                <a
                    onClick={() => {
                        downloadTempVv();
                    }}
                >
                    导入微微薪资参考
                </a>
            </Menu.Item>
            <Menu.Item>
                <a
                    onClick={() => {
                        downloadTemp();
                    }}
                >
                    导入市场薪资参考
                </a>
            </Menu.Item>
        </Menu>
    );

    // 导入数据
    const uploadExcel = v => {
        if (v.file.name.toLowerCase().indexOf('xlsx') > -1 || v.file.name.toLowerCase().indexOf('xls') > -1) {
            const formData = new FormData();
            formData.append('file', v.file);
            fetch('/api/oa/v1/stream/salarystandard/importdata', {
                method: 'POST',
                headers: {
                    Authorization: cookie.get('Authorization'),
                    current_account_user_code: currentUser.userCode
                },
                body: formData
            })
                .then(response => response.json())
                .then(res => {
                    if (res && res.code === 10000) {
                        // 跳转到流程页面
                        history.push(
                            `${salaryWorkFlowUrl}${res.data.hiDataId}&version=${res.data.version}&ftype=import`
                        );
                    } else {
                        Modal.error({
                            title: '导入失败',
                            okText: '知道了',
                            content: (
                                <div
                                    style={{ overflow: 'auto', maxHeight: 300, paddingRight: 15 }}
                                    // eslint-disable-next-line react/no-danger
                                    dangerouslySetInnerHTML={{ __html: xss(res.msg) }}
                                />
                            )
                        });
                    }
                });
        } else {
            message.error('您上传的文件格式不正确,请重新上传！');
        }
    };

    /**
     * 检查是否允许导入数据
     */
    const checkUpload = async () => {
        const res = await checkBeforeUpload({ formKey: 'editSalary' });
        setUploadDisabled(!res.data);
    };

    /**
     * 新增下载导入功能
     * end
     */

    // 获取数据
    const getDict = async () => {
        const result = await request('/api/dict/v1/getList', {
            data: {
                codes: ['salaryStandardName']
            },
            method: 'POST'
        });
        if (result && result.code === 10000) {
            // 过滤掉微微字典
            setDict(
                result.data
                    .filter(item => item.dictValue !== 's2')
                    .map(item => ({ value: item.dictName, text: item.dictName }))
            );
        }
    };

    const handleUpload = () => {
        if (uploadDisabled) {
            message.warn('当前有数据变更申请在进行中，请先完成相关审批！');
        }
        if (urlType === 'salary' && !salaryWorkFlowUrl) {
            message.warn('没有相关的审批流程！');
        }
    };

    /**
     * 页面加载
     */
    React.useEffect(() => {
        getDict();
        checkUpload();
        checkSalaryWorkFlow();
    }, []);

    React.useEffect(() => {
        if (backVersion > 0) {
            handleBackVersion();
        }
    }, [backVersion]);

    React.useEffect(() => {
        eventTrack({
            eventName: 'personnel_management_organization_salaryreference_click',
            pageName: 'personnel_management_organization'
        });
    }, []);

    React.useEffect(() => {
        setFilterDataName(filterType === 'weiwei' ? ['微微'] : dict.map(x => x.text));
        setPagination({ ...pagination, current: 1 });
        setExpkeys([]);
    }, [filterType]);
    const formatter = text => String(text ?? '').replace(/\B(?=(\d{3})+(?!\d))/g, ',');

    const columns = [
        {
            title: '版本列表',
            dataIndex: 'name',
            render: (text, record) => (
                <>
                    <div>{record.updateTime}</div>
                    <div className={styles.rowFlex}>
                        <div>操作人：{record.operator}</div>
                        <div>{record.state === 1 ? '当前版本' : linkOld(record)}</div>
                    </div>
                </>
            )
        }
    ];

    const renderFirstTitle = () => {
        const expandIcon =
            dataSource && dataSource.length > 0 && filterType === 'weiwei' ? (
                <a
                    style={expandStyle}
                    onClick={() => {
                        if (expkeys.length > 0) {
                            // 通过维护id长度来判断是否全部展开与否
                            setExpkeys([]);
                        } else {
                            setExpkeys(dataSource && dataSource.map(item => item.id));
                        }
                    }}
                >
                    {expkeys.length > 0 ? '-' : '+'}
                </a>
            ) : null;
        return (
            <>
                {expandIcon}
                <span style={{ paddingLeft: 10 }}>数据名称</span>
            </>
        );
    };
    const filterCont =
        filterType === 'weiwei' ? {} : { filters: dict, filterMultiple: true, filteredValue: filterDataName || null };
    const remark = {
        title: '备注',
        dataIndex: 'remark'
    };
    const nullRemark = {
        title: '',
        dataIndex: 'nullDataShow'
    };
    const remarkCont = filterType === 'weiwei' ? remark : nullRemark;
    const salaryColumns = [
        {
            title: renderFirstTitle(),
            dataIndex: 'salaryStandardName',
            ...filterCont
        },
        {
            title: '职位类别',
            dataIndex: 'postTypeName',
            sorter: () => {}
        },
        {
            title: '职位名称',
            dataIndex: 'postName',
            sorter: () => {}
        },
        {
            title: '职位代码',
            dataIndex: 'postCode'
            // sorter: () => {}
        },
        {
            title: '一线25分位',
            dataIndex: 'firstLineTwoQuantile',
            formatter
        },
        {
            title: '一线50分位',
            dataIndex: 'firstLineFiveQuantile',
            formatter
        },
        {
            title: '一线75分位',
            dataIndex: 'firstLineSevenQuantile',
            formatter
        },
        {
            title: '一线90分位',
            dataIndex: 'firstLineNineQuantile',
            formatter
        },
        {
            title: '二线25分位',
            dataIndex: 'secondLineTwoQuantile',
            formatter
        },
        {
            title: '二线50分位',
            dataIndex: 'secondLineFiveQuantile',
            formatter
        },
        {
            title: '二线75分位',
            dataIndex: 'secondLineSevenQuantile',
            formatter
        },
        {
            title: '二线90分位',
            dataIndex: 'secondLineNineQuantile',
            formatter
        },
        {
            ...remarkCont
        }
    ];
    const postColumns = [
        {
            title: '微微职位类别',
            dataIndex: 'firstPositionCodeName',
            render: (text, list) => {
                if (list.firstPositionCodeName && list.secondPositionCodeName) {
                    return `${list.firstPositionCodeName}-${list.secondPositionCodeName}`;
                }
                return '';
            }
        },
        {
            title: '微微职位名称',
            dataIndex: 'postName'
        },
        {
            title: '微微职级',
            dataIndex: 'gradeCode'
        },
        {
            title: '微微职位代码',
            // width: 220,
            dataIndex: 'postCode'
        },
        {
            title: '参考数据名称',
            // width: 220,
            dataIndex: 'salaryStandardName'
        },
        {
            title: '参考职位类别',
            // width: 220,
            dataIndex: 'postTypeName'
        },
        {
            title: '参考职位名称',
            // width: 120,
            dataIndex: 'refPostName'
        },
        {
            title: '参考职位代码',
            dataIndex: 'refSalaryPostCode'
        },
        {
            title: '一线城市90分位',
            dataIndex: 'firstLineNineQuantile',
            formatter
        },
        {
            title: '一线城市75分位',
            dataIndex: 'firstLineSevenQuantile',
            formatter
        },
        {
            title: '一线城市50分位',
            dataIndex: 'firstLineFiveQuantile',
            formatter
        },
        {
            title: '一线城市25分位',
            dataIndex: 'firstLineTwoQuantile',
            formatter
        },
        {
            title: '二线城市90分位',
            dataIndex: 'secondLineNineQuantile',
            formatter
        },
        {
            title: '二线城市75分位',
            dataIndex: 'secondLineSevenQuantile',
            formatter
        },
        {
            title: '二线城市50分位',
            dataIndex: 'secondLineFiveQuantile',
            formatter
        },
        {
            title: '二线城市25分位',
            dataIndex: 'secondLineTwoQuantile',
            formatter
        }
    ];
    const handleTable = page => {
        const extra = {};
        setPagination({
            ...pagination,
            ...page,
            ...extra
        });
        setExpkeys([]);
    };
    // 删除原有的表格筛选功能 换成按钮切换筛选
    const changeFilter = type => {
        setFilterType(type);
    };
    const tableChange = (newPagination, filters, sorter) => {
        // 市场数据情况下才需要
        if (filters && filters.salaryStandardName && filterType === 'other') {
            setFilterDataName(filters.salaryStandardName);
            setPagination({ ...pagination, current: 1 });
        }
        if (sorter && sorter.field && sorter.order) {
            setSortCustom(`${sorter.field}|${sorter.order === 'ascend' ? 'asc' : 'desc'}`);
        } else {
            setSortCustom('');
        }
        setExpkeys([]);
    };
    const setClassName = (record, index) => (index === activeIndex ? `${styles['table-row-active']}` : '');
    const handleExpandedChange = expandedRows => {
        setExpkeys(expandedRows);
    };
    return (
        <PageHeaderWrapper>
            <Card
                title="薪资参考"
                extra={
                    <div>
                        {checkCode('system:data:salary:download') ? (
                            <Dropdown overlay={downMenuItem}>
                                <Button type="primary" onClick={e => e.preventDefault()}>
                                    下载模板
                                </Button>
                            </Dropdown>
                        ) : (
                            ''
                        )}
                        {checkCode('system:data:salary:upload') ? (
                            <Upload
                                customRequest={uploadExcel}
                                disabled={uploadDisabled || (urlType === 'salary' ? !salaryWorkFlowUrl : false)}
                                showUploadList={false}
                                accept="excel"
                            >
                                <Button type="primary" ghost style={{ marginLeft: 15 }} onClick={handleUpload}>
                                    导入数据
                                </Button>
                            </Upload>
                        ) : (
                            ''
                        )}
                    </div>
                }
            >
                <div className={styles.left}>
                    <Table
                        columns={columns}
                        dataSource={editionData}
                        bordered
                        pagination={false}
                        loading={editionLoading}
                        rowClassName={setClassName} // 表格行点击高亮
                        onRow={(text, record) => ({
                            onClick: () => {
                                form.resetFields();
                                setVersion(
                                    urlType === 'salary' ? text.salaryStandardVersion : text.postitionSalaryVersion
                                );
                                if (urlType === 'salary') {
                                    setExpkeys([]);
                                    setApplicationNo(text.applicationNo);
                                }
                                setPagination({
                                    ...pagination,
                                    current: 1
                                    // pageSize: 10
                                    // total: 10
                                });
                                setActiveIndex(record);
                            } // 点击行
                        })}
                        // title={() => '版本列表'}
                    />
                    ,
                </div>
                <div className={styles.right}>
                    <SalaryDescription description={description} />
                    <AnchorPart floatStyle={{ zIndex: 100, backgroundColor: '#fff' }} fixedTop={110}>
                        <div style={{ overflow: 'hidden' }}>
                            <QuickSearch
                                form={form}
                                urlType={urlType}
                                pagination={pagination}
                                setPagination={setPagination}
                                search={search}
                                setSearch={setSearch}
                                setExpkeys={setExpkeys}
                            />
                            <div style={{ cssFloat: 'right', marginTop: '23px' }}>
                                <Button.Group>
                                    <Button
                                        type="primary"
                                        className={filterType === 'weiwei' ? styles.radius : styles.blackShow}
                                        onClick={() => {
                                            changeFilter('weiwei');
                                        }}
                                    >
                                        微微数据
                                    </Button>
                                    <Button
                                        type="primary"
                                        className={filterType === 'weiwei' ? styles.blackShow : styles.radius}
                                        onClick={() => {
                                            changeFilter('other');
                                        }}
                                    >
                                        市场数据
                                    </Button>
                                </Button.Group>

                                <Button
                                    type="primary"
                                    ghost
                                    onClick={() => {
                                        history.push({
                                            pathname:
                                                applicationNo.indexOf('-') > 0
                                                    ? '/personal/portal/myAuditRead/myAuditReadDetail'
                                                    : '/office/institutions/flowManage/fullApprovalProcess/processDetail',
                                            query: {
                                                actionShow: 'no',
                                                applicationNo
                                            }
                                        });
                                    }}
                                    style={{ marginLeft: 15 }}
                                >
                                    查看修改内容
                                </Button>
                            </div>
                        </div>
                    </AnchorPart>
                    <AnchorTableHeader thresholdTopOffset={80} fixedTop={156}>
                        <DataUpdate
                            getSource={{
                                dataSource: dataSource === null ? [] : [...dataSource],
                                columns: urlType === 'salary' ? salaryColumns : postColumns
                            }}
                            tableConfig={{
                                modifyType: 'modifyType',
                                difference: 'difference'
                            }}
                            tableProps={{
                                scroll: { x: 'max-content' },
                                rowKey: 'id',
                                loading,
                                onChange: tableChange,
                                expandedRowKeys: expkeys,
                                onExpandedRowsChange: handleExpandedChange
                            }}
                        />
                    </AnchorTableHeader>
                </div>
                <Pagination {...pagination} onChange={handleTable} loading={loading} />
            </Card>
        </PageHeaderWrapper>
    );
};

// export default History;
export default connect(({ user }) => ({ user }))(Form.create()(History));
